﻿$(document).ready(function () {
    $("#frmAddAlbum").submit(function (e) {
        var data = $("#divAlbumForm :input:not(:hidden)").serializeObject();
        data.sections = new Array();
        data.filmingDays = new Array();

        //loop through all sections
        $("ul#Sections li").each(function () {
            var sectionData = $(this).find(":input").serializeObject();

            //add the section to the JSON object
            data.sections.push(sectionData);
        });

        //loop through all filming days
        $("#FilmingDays tr:not(:first)").each(function () {
            var filmingDayData = $(this).find(":input").serializeObject();

            //add the section to the JSON object
            if (filmingDayData.Date != "") {
                data.filmingDays.push(filmingDayData);
            }
        });

        var errorMessage = "";

        //check how many pagesCount are invalid (odd numbers or 0)
        var invalisPagesNumber = 0;
        $("ul#Sections li").each(function () {
            if ($(this).find("[name=PagesCount]:visible").length > 0) {
                var pagesCount = parseInt($(this).find("[name=PagesCount]").val());

                if (pagesCount % 2 != 0 || pagesCount < 2) {
                    invalisPagesNumber++;
                }
            }
        });
        
        //check if Album with this OrderNum already exists
        $.post(pathPrefix + "Albums/IsOrderNumExists", { "OrderNum": $("#OrderNum").val() }, function (result) {
            if (result == false) {
                if (IsAlbumValid(data)) {
                    if (data.sections.length > 0) {
                        if (AreSectionsValid(data.sections)) {
                            if (invalisPagesNumber == 0) {
                                var dialog = updateDialog("פתיחת אלבום חדש", 150, 400);

                                //Invoke AJAX method to add this album to DB
                                $.ajax({
                                    url: pathPrefix + "Albums/Add",
                                    data: JSON.stringify(data),
                                    type: "POST",
                                    dataType: "json",
                                    contentType: 'application/json; charset=utf-8',
                                    success: function (result) {
                                        dialog.html("האלבום נפתח בהצלחה!");

                                        //Invoke ajax method to import images
                                        $.post(pathPrefix + "AlbumFiles/ImportImagesFromDirectory", { "AlbumId": result.AlbumId }, function () { }, "json");

                                        //redirect the user to the AlbumDetails page
                                        window.setTimeout(function () {
                                            window.location = result.Url;
                                        }, 1000);
                                    }
                                });
                            }
                            else {
                                errorMessage = "מספר העמודים בכל מקטע חייב להיות זוגי.";
                            }
                        }
                        else {
                            errorMessage = "נתונים חסרים בפרטי המקטעים.";
                        }
                    }
                    else {
                        errorMessage = "לא הוגדרו מקטעים.";
                    }
                }
                else {
                    errorMessage = "נתונים חסרים בפרטי האלבום.";
                }
            }
            else {
                errorMessage = "מספר הזמנה זה כבר קיים במאגר.";
            }

            //if there was an error
            if (errorMessage != "") {
                var dialog = updateDialog("פתיחת אלבום חדש", 200, 400);
                dialog.html(errorMessage);
            }
        }, "json");

        e.preventDefault();
    });

    function IsAlbumValid(data) {
        var isValid = false;

        //check if album has all the required details
        if (data.Title != "" && data.NumOfPages != "" && data.DueDate != "" && data.OrderNum != "" && data.PaperId != "" && data.EditorPassword != "") {
            isValid = true;
        }
        return isValid;
    }

    function AreSectionsValid(sections) {
        var isValid = true;

        //loop through the sections
        for (var i = 0; i < sections.length; i++) {
            var sectionData = sections[i];
            //check if this section has all the required details
            if (sectionData.SectionTitle != "" && sectionData.AlbumSectionTypeId != "" && sectionData.EditorPassword != "" && sectionData.PagesCount != "") {

            }
            else {
                isValid = false;
            }
        }

        return isValid;
    }

    $("#NumOfPages,[name='PagesCount']").live("change", function () {
        //show or hide the relevant label
        if (CheckPagesCountValid() == false) {
            $("#pagesCountNotEqual").show();
        }
        else {
            $("#pagesCountNotEqual").hide();
        }
    });

    function CheckPagesCountValid() {
        //sum all the pages of sections
        var totalPagesOfSections = 0;
        $("[name='PagesCount']").each(function () {
            totalPagesOfSections += parseInt($(this).val());
        });

        var albumPages = parseInt($("#NumOfPages").val());

        if ($("[name='PagesCount']").length == 0) {
            return true;
        }

        //check if the SectionsPages is the same as the AlbumPages
        return (albumPages == totalPagesOfSections);
    }

    //when the user change the order num
    $("#OrderNum").change(function () {
        //check if Album with this OrderNum already exists
        $.post(pathPrefix + "Albums/IsOrderNumExists", { "OrderNum": $("#OrderNum").val() }, function (result) {
            if (result) {
                $("#orderNumExists").show();
            }
            else {
                $("#orderNumExists").hide();
            }
        }, "json");
    });

    $("#OrderNum").keydown(function () {
        $("#orderNumExists").hide();
    });
});